package com.lans.search;

import java.util.Arrays;

/**
 * @author: lans
 * @date: 2025/3/10
 * @name: 刘宇
 */
public class FibonacciSearch {
    private static int maxSize = 20;
    public static void main(String[] args) {
        int[] arr = {1,4,6,45,64,65,75,3443,23242,42344};
        int i = fibSearch(arr,75);
        System.out.println("i="+i);
    }

    //初始化斐波那契数列 mid = low+F(k-1)-1
    public static int[] fib(){

        int[] f = new int[maxSize];
        f[0]=1;
        f[1]=1;
        for(int i=2;i<maxSize;i++){
            f[i] = f[i-1]+f[i-2];
        }
        return f;
    }

    /**
     * 求出数列中关键字的位置
     */
    public static int fibSearch(int[] arr,int key){
        int low = 0;
        int hight = arr.length-1;
        int mid;

        //斐波那契分割的数值下标
        int k = 0;
        //获取斐波那契数列
        int[] f = fib();

        //获取k的下标值
        while(hight>f[k]-1){
            k++;
        }
        int[] temp = Arrays.copyOf(arr,f[k]);
        for(int i=hight+1;i<temp.length;i++){
            temp[i]=arr[hight];
        }

        //mid = low+F(k-1)-1
        while(low<=hight){
            mid = low+f[k-1]-1;
            if(key<temp[mid]){
                hight=mid-1;
                k--;
            }else if(key>temp[mid]){
                low=mid+1;
                k-=2;
            }else{
                if(mid<=hight){
                    return mid;
                }else{
                    return hight;
                }
            }
        }
        return -1;
    }
}